﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CRM.Entity;
using CRM.BLL;
using System.Text;
using DP.Common;
using DP.Web.UI;

namespace CRM.Web.ComplaintCaseManage
{
    public partial class Assignment : Common.PageBase
    {
        T_USER_BLL userBll = new T_USER_BLL();
        private T_DEPARTMENT_BLL departmentBll = new T_DEPARTMENT_BLL();
        private T_COMPLAINTCASE_BLL complaintCaseBll = new T_COMPLAINTCASE_BLL();

        /// <summary>
        /// 工单状态业务访问对象
        /// </summary>
        private T_WORKORDERSTATUS_BLL workOrderStatusBll = new T_WORKORDERSTATUS_BLL();


        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            PageHelper.SetPrePageUrl(this.Page);
            if (PageHelper.GetQueryString(this.Page, "PageTarget") != "Opener")
            {
                PageHelper.SetGoBackUrl(this.Page, btnCancel, StaticConstant.NotBackUrl);
                btnCancel.Attributes["onclick"] = UserLoginInfo.FilterBackUrl(btnCancel.Attributes["onclick"]);
            }
            else
            {
                PageHelper.SetClose(this.Page, btnCancel);
                btnCancel.Value = "关 闭";
            }
            PageHelper.SetPopCalender(this.Page, txtCREATETIMEBegin);
            PageHelper.SetPopCalender(this.Page, txtCREATETIMEEnd);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                ddlSTATUSBinding();
                ddlDepartmentBinding();
                ddlUserIdBinding();
                ddlUserId_SelectedIndexChanged(ddlUserId, null);
                gvDataBindingUser();
                //pageInit();
            }
        }

        private void ddlSTATUSBinding()
        {
            ddlSTATUS.DataSource =
                           workOrderStatusBll.GetList(String.Format(" and OrderTypeID = '{0}' ",
                                                                    ((int)WorkOrderType.投诉工单).ToString()));

            ddlSTATUS.DataTextField = "ORDERSTATUSNAME";
            ddlSTATUS.DataValueField = "ORDERSTATUSID";
            ddlSTATUS.DataBind();
            ddlSTATUS.Items.Insert(0, new ListItem("", ""));
        }



        private void ddlDepartmentBinding()
        {
            StringBuilder sql = new StringBuilder();
            if (!UserLoginInfo.IsAdministrator())
            {
                sql.Append(" and BUSINESSDIVISIONCODE = '" + _userLoginInfo.UserEntity.BUSINESSDIVISIONCODE.Trim() + "'");

            }
            sql.Append(String.Format(" and ISCENTER = '{0}' ", ((int)DepartmentType.呼叫中心).ToString()));
            sql.Append(" and DepartmentID in (select DepartmentID from T_User ) ");

            ddlDepartment.DataSource = departmentBll.GetList(sql.ToString());
            ddlDepartment.DataTextField = "DEPARTMENTNAME";
            ddlDepartment.DataValueField = "DEPARTMENTID";
            ddlDepartment.DataBind();
            if (!UserLoginInfo.IsAdministrator())
            {
                ddlDepartment.Enabled = false;
                ddlDepartment.SelectedValue = _userLoginInfo.UserEntity.DEPARTMENTID.ToString();
            }

        }

        /// <summary>
        /// DDLs the user id binding.
        /// </summary>
        private void ddlUserIdBinding()
        {
            ddlUserId.DataSource = userBll.GetList(GenerationSQLStringUser().ToString());
            ddlUserId.DataTextField = "USERNAME";
            ddlUserId.DataValueField = "USERID";
            ddlUserId.DataBind();
            ddlUserId.Items.Insert(0, new ListItem("", ""));
        }

        /// <summary>
        /// 生成查询条件字符串
        /// </summary>
        private StringBuilder GenerationSQLStringUser()
        {
            StringBuilder sql = new StringBuilder();
            sql.Append(" and (ISSYSTEMADMIN <> '1' or ISSYSTEMADMIN is null) ");
            sql.Append(String.Format(" and DEPARTMENTID = '{0}' ", ddlDepartment.SelectedValue));
            if (!UserLoginInfo.IsAdministrator())
            {
                sql.Append(" and BUSINESSDIVISIONCODE = '" + _userLoginInfo.UserEntity.BUSINESSDIVISIONCODE.Trim() + "'");

            }
            return sql;

        }
        private StringBuilder GenerationSQLStringComplaintCase()
        {
            StringBuilder sql = new StringBuilder();
            sql.Append(String.Format(" and Status in (select orderstatusid from t_workorderstatus where Type != '{0}' and OrderTypeID = {1} ) ", ((int)StatusType.结束节点).ToString(), ((int)WorkOrderType.投诉工单).ToString()));
            if (!String.IsNullOrEmpty(ddlUserId.SelectedValue.Trim()))
            {
                sql.Append(String.Format(" and CreatePeopleID = '{0}' ", ddlUserId.SelectedValue.Trim()));
            }
            if (!String.IsNullOrEmpty(ddlSTATUS.SelectedValue.Trim()))
            {
                sql.Append(String.Format(" and Status = '{0}' ", ddlSTATUS.SelectedValue.Trim()));
            }
            if (!String.IsNullOrEmpty(txtCREATETIMEBegin.Text.Trim()))
            {
                sql.Append(" and " + complaintCaseBll._dal.GetBeginDateString("CREATETIME", txtCREATETIMEBegin.Text.Trim()) + " ");
            }
            if (!String.IsNullOrEmpty(txtCREATETIMEEnd.Text.Trim()))
            {
                sql.Append(" and " + complaintCaseBll._dal.GetEndDateString("CREATETIME", txtCREATETIMEEnd.Text.Trim()) + " ");
            }
            if (!UserLoginInfo.IsAdministrator())
            {
                sql.Append(" and BUSINESSDIVISIONCODE = '" + _userLoginInfo.UserEntity.BUSINESSDIVISIONCODE.Trim() + "'");
            }
            return sql;
        }

        protected void ddlSTATUS_SelectedIndexChanged(object sender, EventArgs e)
        {
            gvDataBindingComplaintCase();
        }

        /// <summary>
        /// 页面数据绑定
        /// </summary>
        private void gvDataBindingUser()
        {
            #region 查询条件字符串
            StringBuilder sql = GenerationSQLStringUser();
            #endregion

            List<T_USER_Entity> list;

            //获取总的记录条数
            gvList.RecordCount = (int)userBll.GetCount(sql.ToString());

            list = userBll.GetList(sql.ToString(), gvList.SortConditions);

            gvList.DataSource = list;
            gvList.DataKeyNames = new string[] { "USERID", "UserName", "LoginName" };
            gvList.DataBind();

        }

        private void gvDataBindingComplaintCase()
        {
            #region 查询条件字符串
            StringBuilder sql = GenerationSQLStringComplaintCase();
            #endregion

            List<T_COMPLAINTCASE_Entity> list;

            //获取总的记录条数
            gvListComplaintCase.RecordCount = (int)complaintCaseBll.GetCount(sql.ToString());

            list = complaintCaseBll.GetList(sql.ToString(), gvListComplaintCase.SortConditions);

            gvListComplaintCase.DataSource = list;
            gvListComplaintCase.DataKeyNames = new string[] { "CASEID", "ToDoReminderTime" };
            gvListComplaintCase.DataBind();
        }


        protected void ddlDepartment_SelectedIndexChanged(object sender, EventArgs e)
        {
            gvDataBindingUser();
            ddlUserIdBinding();
            ddlUserId_SelectedIndexChanged(ddlUserId, null);
        }

        protected void ddlUserId_SelectedIndexChanged(object sender, EventArgs e)
        {
            gvDataBindingComplaintCase();
        }




        protected void btnAssign_Click(object sender, EventArgs e)
        {
            List<T_USER_Entity> userList = GetSelected(gvList);
            if (userList.Count == 0)
            {
                PageHelper.ShowMessage(this.Page, "请选择分配的目标人！");
                return;
            }
            List<T_COMPLAINTCASE_Entity> complaintCaseList = GetSelectedComplaintCase(gvListComplaintCase);

            try
            {
                for (int i = 0; i < complaintCaseList.Count; i++)
                {
                    complaintCaseList[i].HELPUSERID = userList[(i % userList.Count)].USERID;
                    complaintCaseList[i].HELPUSERNAME = userList[i % userList.Count].USERNAME;
                    complaintCaseBll.Update(complaintCaseList[i]);
                }
                gvDataBindingComplaintCase();
                PageHelper.ShowMessage(this.Page, "分配成功！");
            }
            catch (Exception ex)
            {
                PageHelper.ShowMessage(this.Page, "分配失败！");
            }


        }

        private List<T_USER_Entity> GetSelected(GridView gv)
        {
            List<T_USER_Entity> list = new List<T_USER_Entity>();
            if (gv == null) return list;
            T_USER_Entity entity;
            CheckBox cb;
            foreach (GridViewRow gvr in gv.Rows)
            {
                cb = gvr.FindControl("cbItem") as CheckBox;
                if (cb == null) continue;
                if (!cb.Checked) continue;
                entity = new T_USER_Entity();
                entity.USERID = StringHelper.ToInt(gv.DataKeys[gvr.RowIndex].Values["USERID"].ToString(), 0);
                entity.USERNAME = gv.DataKeys[gvr.RowIndex].Values["UserName"].ToString();
                entity.LOGINNAME = gv.DataKeys[gvr.RowIndex].Values["LoginName"].ToString();
                list.Add(entity);
            }
            return list;
        }

        private List<T_COMPLAINTCASE_Entity> GetSelectedComplaintCase(GridView gv)
        {
            List<T_COMPLAINTCASE_Entity> sublist = new List<T_COMPLAINTCASE_Entity>();
            if (gv == null) return sublist;
            List<T_COMPLAINTCASE_Entity> list = complaintCaseBll.GetList(GenerationSQLStringComplaintCase().ToString(), gvListComplaintCase.SortConditions);
            T_COMPLAINTCASE_Entity entity;
            CheckBox cb;
            foreach (GridViewRow gvr in gv.Rows)
            {
                cb = gvr.FindControl("cbItem") as CheckBox;
                if (cb == null) continue;
                if (!cb.Checked) continue;
                entity = list.Find(p =>
                {
                    if (p.CASEID.ToString() == gv.DataKeys[gvr.RowIndex].Values["CASEID"].ToString())
                        return true;
                    else
                        return false;
                });
                if (entity != null)
                {
                    sublist.Add(entity);
                }
            }
            return sublist;
        }


        protected void gvListComplaintCase_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            string temp = string.Empty;
            switch (e.Row.RowType)
            {
                case DataControlRowType.DataRow:
                    {
                        GridView gv = (sender as GridView);
                        for (int i = 0; i < gv.Columns.Count; i++)
                        {
                            BoundField bf = gv.Columns[i] as BoundField;
                            if (bf != null)
                            {
                                #region 存储值 转换成  显示值

                                switch (bf.DataField)
                                {

                                    case "STATUS":
                                        {
                                            temp = e.Row.Cells[i].Text.Trim();
                                            T_WORKORDERSTATUS_Entity entity =
                                                workOrderStatusBll.GetPageItem_T_WORKORDERSTATUS_EntityByKey(this.Page, StringHelper.ToInt(temp, 0));
                                            if (entity != null)
                                            {
                                                temp = entity.ORDERSTATUSNAME;
                                                if (!String.IsNullOrEmpty(entity.RECORDSTYLE))
                                                {
                                                    e.Row.Attributes["style"] = entity.RECORDSTYLE;

                                                }
                                            }
                                            e.Row.Cells[i].Text = temp;
                                        }
                                        break;
                                    default:
                                        {

                                        }
                                        break;
                                }

                                #endregion
                            }
                        }
                        #region 超期样式
                        DateTime dt = DateTime.Now;
                        temp = (gv.DataKeys[e.Row.RowIndex].Values["ToDoReminderTime"] == null)
                                   ? "" : gv.DataKeys[e.Row.RowIndex].Values["ToDoReminderTime"].ToString();
                        if (DateTime.TryParse(temp, out dt))
                        {
                            if (dt.CompareTo(DateTime.Now) < 0)
                            {
                                try
                                {
                                    e.Row.Attributes["style"] = configBll.GetCacheValueByName(this.Page, "ExtendedStyle");
                                }
                                catch (Exception)
                                {

                                }
                            }
                        }
                        #endregion
                    }
                    break;
                case DataControlRowType.Header:
                    {

                    }
                    break;
                case DataControlRowType.Pager:
                    {

                    }
                    break;
                case DataControlRowType.EmptyDataRow:
                    {


                    }
                    break;
                default:

                    break;
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            gvDataBindingComplaintCase();
        }
    }
}
